package yyee.llee.mmee.weather.base

import android.text.TextUtils
import com.jhweather.net.ApiManager
import com.jhweather.net.response.BaseResponse
import yyee.llee.mmee.base_api_net.base_api_bean.bean.BaseResult
import yyee.llee.mmee.net.api.IServiceApi
import yyee.llee.mmee.net.response.BaseResponseForJH
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.coroutineScope
import java.io.IOException

/**
 * <p>Repository基类</p >
 */
open class BaseRepository {

    val mApiManager = ApiManager.createApi(IServiceApi::class.java)

    suspend fun <T : Any> safeApiCall(
        call: suspend () -> BaseResult<T>,
        errorMessage: String,
    ): BaseResult<T> {
        return try {
            call()
        } catch (e: Throwable) {
            if (TextUtils.isEmpty(e.message)) {
                BaseResult.Error(
                    IOException(
                        errorMessage,
                        e
                    )
                )
            } else {
                BaseResult.Error(
                    IOException(
                        e.message,
                        e
                    )
                )
            }
        }
    }


    suspend fun <T : Any> executeResponseForJH(
        response: BaseResponseForJH<T>,
        successBlock: (suspend CoroutineScope.() -> Unit)? = null,
        errorBlock: (suspend CoroutineScope.() -> Unit)? = null,
    ): BaseResult<T> {
        return coroutineScope {
            if (!response.error_code.equals("0")) {
                errorBlock?.let { it() }
                BaseResult.Error(IOException(response.reason))
            } else {
                successBlock?.let { it() }
                BaseResult.Success(response.result)
            }
        }
    }


    suspend fun <T : Any> executeResponse(
        response: BaseResponse<T>,
        successBlock: (suspend CoroutineScope.() -> Unit)? = null,
        errorBlock: (suspend CoroutineScope.() -> Unit)? = null,
    ): BaseResult<T> {
        return coroutineScope {
            if (!response.code.equals("0")) {
                errorBlock?.let { it() }
                BaseResult.Error(IOException(response.msg))
            } else {
                successBlock?.let { it() }
                BaseResult.Success(response.data)
            }
        }
    }
}